<template>
    <div v-loading="loading" element-loading-text="拼命加载中">
        <div class="content_top">
            <el-row>
                <el-col :span="12">
                    <span v-if="goodsId === null">新增商品</span>
                    <span v-if="goodsId !== null">修改商品</span>
                </el-col>
                <el-col :span="12" style="text-align: right">
                    <el-button icon="el-icon-back" type="default" circle size="mini" @click="back"></el-button>
                </el-col>
            </el-row>
        </div>

        <div class="content">
            <el-form ref="form" :model="form" :rules="rules" label-width="95px" size="mini">
                <el-form-item label="商品名称：" prop="name">
                    <el-input v-model="form.name" style="width: 305px;"></el-input>
                </el-form-item>
                <el-form-item label="商品编号：" prop="goodsNo">
                    <el-input v-model="form.goodsNo" style="width: 305px;"></el-input>
                </el-form-item>
                <el-form-item label="商品分类：" prop="category">
                    <el-cascader :options="category.data" v-model="form.category" :props="category.props" style="width: 305px;">
                    </el-cascader>
                </el-form-item>
                <el-form-item label="上限系数：" prop="upLimit">
                    <el-input-number v-model="form.upLimit" :min="0" :precision="2" style="width: 305px;"></el-input-number>
                </el-form-item>
                <el-form-item label="下限系数：" prop="downLimit">
                    <el-input-number v-model="form.downLimit" :min="0" :precision="2" style="width: 305px;"></el-input-number>
                </el-form-item>

                <el-form-item label="进货成本：" prop="costPrice">
                    <el-input-number v-model="form.costPrice" :min="0" :precision="2" style="width: 305px;" @change="onAdvisePriceChange"></el-input-number>
                </el-form-item>
                <el-form-item label="加价率：" prop="plusRate">
                    <el-input-number v-model="form.plusRate" :min="0" :precision="2" style="width: 305px;" @change="onAdvisePriceChange"></el-input-number>
                </el-form-item>
                <el-form-item label="建议单价：" prop="adviseUnitPrice">
                    <el-input-number v-model="form.adviseUnitPrice" :min="0" :precision="2" style="width: 305px;"></el-input-number>
                </el-form-item>

                <el-form-item label="类型：" prop="promotion">
                    <el-radio-group v-model="form.goodsSpec" @change="promotionChange" :disabled="goodsId !== null">
                        <el-radio :label="1">标准</el-radio>
                        <el-radio :label="2">称重</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="单价：" prop="unitPrice" v-if="form.goodsSpec === 2">
                    <el-input-number v-model="form.unitPrice" :min="0" :precision="2" style="width: 305px;" @change="onPriceChange"></el-input-number>
                    <span class="lable-remark"> 元/500克</span>
                </el-form-item>
                <el-form-item label="重量：" prop="weight" v-if="form.goodsSpec === 2">
                    <el-input-number v-model="form.weight" :min="0" :precision="2" style="width: 305px;" @change="onPriceChange"></el-input-number>
                    <span class="lable-remark">克</span>
                </el-form-item>
                <el-form-item label="售价：" prop="price">
                    <el-input-number v-model="form.price" :min="0" :precision="2" style="width: 305px;"></el-input-number>
                </el-form-item>
                <el-form-item label="促销：" prop="promotion">
                    <el-radio-group v-model="form.promotion" @change="promotionChange" :disabled="goodsId !== null">
                        <el-radio :label="0">无</el-radio>
                        <!--<el-radio :label="1">特价</el-radio>-->
                        <el-radio :label="2">限购</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="促销售价：" prop="promotionPrice" v-if="form.promotion > 0">
                    <el-input-number v-model="form.promotionPrice" :min="0" :precision="2" style="width: 305px;" :disabled="goodsId !== null"></el-input-number>
                    <span style="color: red; font-size: 8px;">&nbsp;&nbsp;元/份</span>
                </el-form-item>
                <el-form-item label="购物车数：" prop="cartCount">
                    <el-input-number v-model="form.cartCount" :min="1" style="width: 305px;" :disabled="form.promotion === 2"></el-input-number>
                    <span style="color: red; font-size: 8px;">&nbsp;&nbsp;允许同时购物车存在的商品数量（限购商品默认1次）</span>
                </el-form-item>
                <el-form-item label="排序码：" prop="sort">
                    <el-input-number v-model="form.sort" :min="0" style="width: 305px;"></el-input-number>
                </el-form-item>
                <el-form-item label="封面图：" prop="image">
                    <image-upload ref="uploadImage" :limit="1" :isThumbnails="1" :width="400" :height="400" v-model="form.image"></image-upload>
                </el-form-item>
                <el-form-item label="详情图：" prop="images">
                    <image-upload ref="uploadImages" :limit="8" v-model="form.images"></image-upload>
                </el-form-item>
                <el-form-item label="描述：" prop="introduce">
                    <el-input type="textarea" v-model="form.introduce" style="width: 305px;"></el-input>
                </el-form-item>
                <el-form-item label="备注：" prop="remark">
                    <el-input type="textarea" v-model="form.remark" style="width: 305px;"></el-input>
                </el-form-item>
                <el-form-item style="text-align: center; width: 400px">
                    <el-button type="primary" @click="onSubmit">保存</el-button>
                    <el-button @click="$router.back()">取消</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
    import cal from '@/utils/calculation'
    import ImageUpload from '@/components/common/upload/ImageUpload'
    import {categoryTree} from '@/api/goods/goods-category'
    import {addGoods, modifyGoods, goodsInfo} from '@/api/goods/goods'

    export default {
        name: 'GoodsSave',
        components: {
            "image-upload": ImageUpload
        },
        data() {
            return {
                loading: false,
                goodsId: null,
                category: {
                    props: {label: 'name', value: 'id'},
                    data: [],
                    selected: null
                },
                form: {
                    name: null,
                    goodsNo: null,
                    category: null,

                    upLimit: 0,
                    downLimit: 0,
                    costPrice: 0,
                    plusRate: 0,
                    adviseUnitPrice: 0,

                    goodsSpec: 1,
                    unitPrice: 0,
                    weight: 0,
                    price: 0,
                    promotion: 0,
                    promotionPrice: 0,
                    cartCount: 1,
                    sort: 0,
                    image: [],
                    images: [],
                    introduce: null,
                    remark: null
                },
                rules: {
                    name: [
                        {required: true, message: '请输入商品名称', trigger: 'blur'},
                        {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
                    ],
                    goodsNo: [
                        {required: true, message: '请输入商品编号', trigger: 'blur'},
                        {min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur'}
                    ],
                    category: [
                        {required: true, message: '请选择商品分类', trigger: 'blur'},
                    ],
                    unitPrice: [
                        {required: true, message: '请输入单价', trigger: 'blur'},
                    ],
                    weight: [
                        {required: true, message: '请输入重量', trigger: 'blur'},
                    ],
                    price: [
                        {required: true, message: '请输入售价', trigger: 'blur'},
                    ],
                    sort: [
                        {required: true, message: '请输入排序码', trigger: 'blur'},
                    ],
                    cartCount: [
                        {required: true, message: '请输入购物车最大数量', trigger: 'blur'},
                    ],
                    image: [
                        {required: true, message: '请上传封面图', trigger: 'blur'},
                    ],
                    // images: [
                    //     {required: true, message: '请至少上传一张商品图片', trigger: 'blur'},
                    // ],
                    introduce: [
                        {min: 0, max: 255, message: '长度在 0 到 255 个字符', trigger: 'blur'}
                    ],
                    remark: [
                        {min: 0, max: 255, message: '长度在 0 到 255 个字符', trigger: 'blur'}
                    ]
                }
            }
        },
        mounted() {
            this.loadCategory()
            this.goodsId = window.localStorage.getItem("goodsId")
            if (this.goodsId) {
                this.loadGoodsInfo()
            }
        },
        methods: {
            async loadCategory() {
                let res = await categoryTree()
                if (res.code !== "0") return
                this.category.data = res.data[0].children
            },
            async loadGoodsInfo() {
                this.loading = true
                let res = await goodsInfo(this.goodsId)
                this.loading = false
                let data = res.data.goods;

                let images = [];
                res.data.images.forEach(item => {
                    images.push(item.image)
                })

                data.category = [data.category]
                data.image = [data.image]
                data.images = images
                this.form = data
            },
            back() {
                this.$router.back()
            },
            promotionChange() {
                if (this.form.promotion === 2) {
                    this.form.cartCount = 1
                }
            },
            onPriceChange () {
                let temp = cal.accDiv(this.form.unitPrice, 500)
                this.form.price = cal.accMul(temp, this.form.weight)
            },
            onAdvisePriceChange () {
                if (!this.form.costPrice || this.form.costPrice === 0) return
                if (!this.form.plusRate || this.form.plusRate === 0) return
                this.form.adviseUnitPrice = cal.accDiv(this.form.costPrice, this.form.plusRate)
            },
            onSubmit() {
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        this.save()
                    } else {
                        return false;
                    }
                });
            },
            async save() {
                this.loading = true;
                let params = JSON.parse(JSON.stringify(this.form))
                params.category = this.form.category[0]
                params.image = this.form.image[0]
                let res = null;
                if (this.goodsId === null) {
                    res = await addGoods(params)
                } else {
                    res = await modifyGoods(this.goodsId, params)
                }

                this.loading = false
                if (res.code !== '0') {
                    return this.$notify.error({title: '消息', message: res.message})
                }
                this.$notify({title: '消息', message: '保存成功', type: 'success'});
                if (!this.goodsId) {
                    this.$refs.form.resetFields();
                    this.$refs.uploadImage.clear()
                    this.$refs.uploadImages.clear()
                }
            }
        }
    }
</script>

<style scoped>
    .lable-remark {
        font-size: 10px;
        color: red;
        padding-left: 10px;
    }
</style>
